import { constantRoutes } from '@/router'
import apiUser from '@/api/user'
import Layout from '@/layout'

/**
 * 判断用户是否拥有权限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 路由过滤
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      const component = tmp.component;
      if (route.component){
        if (component === "Layout"){
          tmp.component = Layout;
        }else {
          // 从权限数据库表查询url信息映射为组件信息
          tmp.component= () => import(`@/views${component}`)
        }
      }
      // 封装子组件信息
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  /**
   * 设置路由
   * @param state
   * @param routes
   * @constructor
   */
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve,reject) => {
      apiUser.getRouteList().then(res=>{
        let accessedRoutes;
        if (res.status===true){
          accessedRoutes = filterAsyncRoutes(res.data, roles)
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(err=>{
        reject(err);
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
